<template>
    <div class="user-control">
        <el-card class="control-card">
            <template #header>
                <div class="card-header">
                    <h2>用户管理</h2>
                    <el-button type="primary" @click="handleAdd">新增用户</el-button>
                </div>
            </template>

            <!-- 搜索区域 -->
            <el-form :inline="true" :model="searchForm" class="search-form">
                <el-form-item label="用户ID">
                    <el-input v-model="searchForm.id" placeholder="请输入用户ID" clearable />
                </el-form-item>
                <el-form-item label="用户名">
                    <el-input v-model="searchForm.userName" placeholder="请输入用户名" clearable />
                </el-form-item>
                <el-form-item label="用户角色">
                    <el-select v-model="searchForm.userRole" placeholder="请选择角色" clearable>
                        <el-option label="管理员" value="admin" />
                        <el-option label="普通用户" value="user" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">搜索</el-button>
                    <el-button @click="resetSearch">重置</el-button>
                </el-form-item>
            </el-form>

            <!-- 用户列表 -->
            <el-table :data="userList" style="width: 100%" v-loading="loading">
                <el-table-column prop="id" label="用户ID" width="100" />
                <el-table-column prop="userName" label="用户名" width="120" />
                <el-table-column prop="userAccount" label="账号" width="120" />
                <el-table-column prop="userRole" label="角色" width="100">
                    <template #default="scope">
                        <el-tag :type="scope.row.userRole === 'admin' ? 'danger' : 'success'">
                            {{ scope.row.userRole === 'admin' ? '管理员' : '普通用户' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="userProfile"
                    label="简介"
                    min-width="200"
                    show-overflow-tooltip
                />
                <el-table-column prop="balance" label="余额" width="120">
                    <template #default="scope">¥{{ scope.row.balance }}</template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间" width="180" />
                <el-table-column label="操作" width="200" fixed="right">
                    <template #default="scope">
                        <el-button type="primary" link @click="handleEdit(scope.row)"
                            >编辑</el-button
                        >
                        <el-button type="danger" link @click="handleDelete(scope.row)"
                            >删除</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-container">
                <el-pagination
                    v-model:current-page="currentPage"
                    v-model:page-size="pageSize"
                    :page-sizes="[10, 20, 50, 100]"
                    :total="total"
                    layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                />
            </div>
        </el-card>

        <!-- 用户表单对话框 -->
        <el-dialog
            v-model="dialogVisible"
            :title="dialogType === 'add' ? '新增用户' : '编辑用户'"
            width="500px"
        >
            <el-form
                ref="formRef"
                :model="form"
                :rules="rules"
                label-width="100px"
                label-position="left"
            >
                <el-form-item label="用户名" prop="userName">
                    <el-input v-model="form.userName" placeholder="请输入用户名" />
                </el-form-item>
                <el-form-item label="账号" prop="userAccount" v-if="dialogType === 'add'">
                    <el-input v-model="form.userAccount" placeholder="请输入账号" />
                </el-form-item>
                <el-form-item label="角色" prop="userRole">
                    <el-select v-model="form.userRole" placeholder="请选择角色">
                        <el-option label="管理员" value="admin" />
                        <el-option label="普通用户" value="user" />
                    </el-select>
                </el-form-item>
                <el-form-item label="简介" prop="userProfile">
                    <el-input
                        v-model="form.userProfile"
                        type="textarea"
                        :rows="3"
                        placeholder="请输入用户简介"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
                        确定
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { listUserByPage, addUser, updateUser, deleteUser } from '@/api/user'

// 搜索表单
const searchForm = ref({
    id: '',
    userName: '',
    userRole: ''
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 用户列表
const userList = ref([])
const loading = ref(false)

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const submitLoading = ref(false)
const formRef = ref()

// 表单数据
const form = ref({
    id: null,
    userName: '',
    userAccount: '',
    userRole: '',
    userProfile: ''
})

// 表单验证规则
const rules = {
    userName: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    userAccount: [
        { required: true, message: '请输入账号', trigger: 'blur' },
        { min: 4, max: 20, message: '长度在 4 到 20 个字符', trigger: 'blur' }
    ],
    userRole: [{ required: true, message: '请选择角色', trigger: 'change' }]
}

// 获取用户列表
const fetchUserList = async () => {
    loading.value = true
    try {
        const res = await listUserByPage({
            current: currentPage.value,
            pageSize: pageSize.value,
            ...searchForm.value
        })
        if (res.code === 0) {
            userList.value = res.data.records
            total.value = res.data.total
        } else {
            ElMessage.error(res.message || '获取用户列表失败')
        }
    } catch (error) {
        ElMessage.error(error.message || '获取用户列表失败')
    } finally {
        loading.value = false
    }
}

// 搜索
const handleSearch = () => {
    currentPage.value = 1
    fetchUserList()
}

// 重置搜索
const resetSearch = () => {
    searchForm.value = {
        id: '',
        userName: '',
        userRole: ''
    }
    handleSearch()
}

// 新增用户
const handleAdd = () => {
    dialogType.value = 'add'
    form.value = {
        userName: '',
        userAccount: '',
        userRole: '',
        userProfile: ''
    }
    dialogVisible.value = true
}

// 编辑用户
const handleEdit = row => {
    dialogType.value = 'edit'
    form.value = {
        id: row.id,
        userName: row.userName,
        userRole: row.userRole,
        userProfile: row.userProfile
    }
    dialogVisible.value = true
}

// 删除用户
const handleDelete = row => {
    ElMessageBox.confirm('确定要删除该用户吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            const res = await deleteUser({ id: row.id })
            if (res.code === 0) {
                ElMessage.success('删除成功')
                fetchUserList()
            } else {
                ElMessage.error(res.message || '删除失败')
            }
        } catch (error) {
            ElMessage.error(error.message || '删除失败')
        }
    })
}

// 提交表单
const handleSubmit = async () => {
    if (!formRef.value) return

    try {
        await formRef.value.validate()
        submitLoading.value = true

        const api = dialogType.value === 'add' ? addUser : updateUser
        const res = await api(form.value)

        if (res.code === 0) {
            ElMessage.success(dialogType.value === 'add' ? '新增成功' : '更新成功')
            dialogVisible.value = false
            fetchUserList()
        } else {
            ElMessage.error(res.message || (dialogType.value === 'add' ? '新增失败' : '更新失败'))
        }
    } catch (error) {
        ElMessage.error(error.message || '表单验证失败')
    } finally {
        submitLoading.value = false
    }
}

// 分页相关方法
const handleSizeChange = val => {
    pageSize.value = val
    fetchUserList()
}

const handleCurrentChange = val => {
    currentPage.value = val
    fetchUserList()
}

onMounted(() => {
    fetchUserList()
})
</script>

<style lang="less" scoped>
.user-control {
    padding: 20px;
}

.control-card {
    margin-bottom: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    h2 {
        margin: 0;
        font-size: 20px;
    }
}

.search-form {
    margin-bottom: 20px;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}

:deep(.el-form-item__label) {
    font-weight: 500;
}
</style>
